# -*- coding: utf-8 -*-
"""
连接状态管理器模块
统一管理连接状态，避免重复的状态管理逻辑
"""

from PySide2.QtCore import QObject, Signal
from gglobal import logger


class ConnectionStateManager(QObject):
    """连接状态管理器"""
    
    # 信号定义
    connection_status_changed = Signal(bool, str)  # 连接状态变化 (是否连接, 消息)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._is_connected = False
        self._current_device_ip = None
        self._connection_message = ""
        
        logger.info("连接状态管理器初始化完成")
    
    @property
    def is_connected(self):
        """获取连接状态"""
        return self._is_connected
    
    @property
    def current_device_ip(self):
        """获取当前连接的设备IP"""
        return self._current_device_ip
    
    @property
    def connection_message(self):
        """获取连接消息"""
        return self._connection_message
    
    def set_connected(self, connected, device_ip=None, message=""):
        """设置连接状态
        
        参数:
            connected: 是否连接
            device_ip: 设备IP地址
            message: 连接消息
        """
        # 检查状态或消息是否改变
        status_changed = self._is_connected != connected
        message_changed = self._connection_message != message
        
        self._is_connected = connected
        self._connection_message = message
        
        if connected:
            self._current_device_ip = device_ip
            logger.info(f"连接状态更新: 已连接到 {device_ip}")
        else:
            if not message or "连接已断开" not in message:
                # 连接失败的情况
                logger.warning(f"连接失败: {message}")
            else:
                # 正常断开连接
                logger.info("连接已断开")
            self._current_device_ip = None
        
        # 状态改变或消息改变时都发送信号，确保UI能及时更新
        if status_changed or message_changed:
            self.connection_status_changed.emit(connected, message)
    
    def disconnect(self, is_manual=True):
        """断开连接
        
        参数:
            is_manual: 是否为手动断开连接，默认True
        """
        if self._is_connected:
            if is_manual:
                self.set_connected(False, message="手动断开连接")
            else:
                self.set_connected(False, message="连接已断开")
    
    def reset(self):
        """重置连接状态"""
        self._is_connected = False
        self._current_device_ip = None
        self._connection_message = ""
        logger.info("连接状态已重置")
    
    def get_status_info(self):
        """获取状态信息
        
        返回:
            dict: 包含连接状态信息的字典
        """
        return {
            'is_connected': self._is_connected,
            'device_ip': self._current_device_ip,
            'message': self._connection_message
        }


class ScanStateManager(QObject):
    """扫描状态管理器"""
    
    # 信号定义
    scan_status_changed = Signal(bool)  # 扫描状态变化
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._is_scanning = False
        
        logger.info("扫描状态管理器初始化完成")
    
    @property
    def is_scanning(self):
        """获取扫描状态"""
        return self._is_scanning
    
    def set_scanning(self, scanning):
        """设置扫描状态
        
        参数:
            scanning: 是否正在扫描
        """
        if self._is_scanning != scanning:
            self._is_scanning = scanning
            self.scan_status_changed.emit(scanning)
            
            if scanning:
                logger.info("开始扫描")
            else:
                logger.info("扫描结束")
    
    def start_scan(self):
        """开始扫描"""
        self.set_scanning(True)
    
    def stop_scan(self):
        """停止扫描"""
        self.set_scanning(False)
    
    def reset(self):
        """重置扫描状态"""
        self._is_scanning = False
        logger.info("扫描状态已重置")